var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
const JWT = require('./utils/JWT');
const mongoose = require('mongoose');

const { UserModel } = require('./models');

// 路由
var indexRouter = require('./routes/index');
const { UserRouter, NewsRouter, ProductRouter, RouterRouter, DictRouter } = require('./routes/admin');
const UploadRouter = require('./routes/upload/UploadRouter');
const VideoRouter = require('./routes/video/VideoRouter');

var app = express();

// `CORS`主要的实现方式是服务端通过对响应头的设置，接收跨域请求的处理。
app.use(
  // cors({
  //   origin: '*',
  //   methods: ['GET', 'POST'],
  //   allowedHeaders: ['Authorization', 'Content-Type'],
  //   credentials: true,
  // })
  cors()
);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// admin
// 判断token是否失效
app.use((req, res, next) => {
  // 登陆注册不需要验证token
  if (['/adminApi/user/login', '/adminApi/user/register', '/adminApi/qiniu', '/adminApi/minio'].includes(req.url)) {
    console.log('token失效', req.url);
    next();
  } else {
    console.log('token失效', req.url);
    const { authorization = '' } = req.headers;
    const token = authorization.split(' ')[1] || null;

    if (token) {
      console.log('token有效');
      const payload = JWT.verifyToken(token);
      if (payload) {
        const newToken = JWT.generateToken({
          _id: payload._id,
          username: payload.username,
        });
        // 重新设置token
        res.header('Authorization', newToken);
        res.setHeader('Access-Control-Expose-Headers', 'Authorization'); //  手动添加返回头部
        next();
      } else {
        res.status(401).send({ code: 0, msg: 'token失效' });
      }
    } else {
      //token 不存在
      res.status(401).send({ code: 0, msg: 'token失效' });
    }
  }
});
// 上传文件 公共
app.use(UploadRouter); // 上传文件  七牛云 本地minio
app.use(VideoRouter); // 上传文件

app.use(UserRouter); // 用户
app.use(NewsRouter); //  新闻
app.use(ProductRouter); // 产品
app.use(RouterRouter); // 路由
app.use(DictRouter); // 字典

// web

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 添加超级管理员
(async () => {
  // 连接数据库
  // mongoose.connect('mongodb://127.0.0.1:27017/company-system');
  // 连接成功
  try {
    mongoose.connection.on('connected', () => {
      console.log('数据库连接成功');
      // 查询数据库中是否有超级管理员
      UserModel.findOne({ username: 'superAdmin' }).then(async result => {
        if (!result) {
          // 没有超级管理员
          const user = {
            username: 'superAdmin',
            password: '123456',
            role: 1,
            gender: 0,
            introduction: '超级管理员',
            avatar: 'https://avatars.githubusercontent.com/u/26606204?v=4',
          };
          UserModel.create({ ...user });
          console.log('创建成功超级管理员');
        } else {
          console.log('超级管理员已存在');
        }
      });
    });
  } catch (error) {
    console.log('数据库连接失败' + error);
  }
})();

module.exports = app;
